package com.raycloud.erp.omll.provider.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.Method;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.omall.open.sdk.OmallPageResponse;
import com.omall.open.sdk.domain.OrderDetail;
import com.omall.open.sdk.domain.OrderListInfo;
import com.omall.open.sdk.domain.RefundInfo;
import com.omall.open.sdk.response.OrderDetailResponse;
import com.omall.open.sdk.response.OrderIndexResponse;
import com.omall.open.sdk.response.RefundResponse;
import com.raycloud.erp.omll.data.entity.MulPlatformUser;
import com.raycloud.erp.omll.data.entity.Trade;
import com.raycloud.erp.omll.data.service.OmallSyncInfoService;
import com.raycloud.erp.omll.data.service.OrderService;
import com.raycloud.erp.omll.data.service.TradeService;
import com.raycloud.erp.omll.provider.constant.Constants;
import com.raycloud.erp.omll.provider.model.bo.OrderDetailBO;
import com.raycloud.erp.omll.provider.model.bo.OrderIndexQueryBO;
import com.raycloud.erp.omll.provider.model.bo.ReturnOrderIndexBO;
import com.raycloud.erp.omll.provider.model.bo.TbTradeBO;
import com.raycloud.erp.omll.provider.model.vo.OrderCopierVo;
import com.raycloud.erp.omll.provider.model.vo.TradeCopierVo;
import com.raycloud.erp.omll.provider.service.OrderIndexService;
import com.raycloud.erp.omll.provider.utils.OmallHttpUtils;
import com.raycloud.erp.omll.provider.utils.TradeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author 枫伦
 * @DESCRIPTION
 * @create 2021/1/6 11:09 上午
 */
@Service
@Slf4j
public class OrderIndexServiceImpl implements OrderIndexService {
    @Autowired
    private OmallHttpUtils omallHttpUtils;

    @Autowired
    private OmallTradeCopier omallTradeCopier;

    @Autowired
    private TradeService tradeService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OmallSyncInfoService omallSyncInfoService;

    /***
     * @DESCRIPTION: 订单查询
     * 由于洋葱平台的规定，订单支付成功2-3个小时后，订单才会提供给到商家获取，建议使用商家获取订单时间进行查询
     * @author 枫伦
     * @params: []
     * @return: void
     * @Date: 2021/1/6 12:55 下午
     * @Modified By:
     * @param
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveOrderFromChannel(OrderIndexQueryBO orderIndexQueryBO, MulPlatformUser mulPlatformUser) {
        Map headmap = new HashMap();
        headmap.put(Constants.HEADER_TOKEN_STR, mulPlatformUser.getToken());
        headmap.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        //确定订单总页数
        OmallPageResponse omallPageResponse = (OmallPageResponse) omallHttpUtils.getPageArgs(Method.POST, Constants.RequestUrl.ORDER_INDEX, headmap, omallHttpUtils.Obj2Map(orderIndexQueryBO));
        if (omallPageResponse.getTotalPage() > 0) {
            //订单开始入库
            for (int i = 1; i <= omallPageResponse.getTotalPage(); i++) {
                OrderIndexResponse orderIndexResponse = (OrderIndexResponse) omallHttpUtils.requestWithParams(Method.POST, Constants.RequestUrl.ORDER_INDEX, headmap, OrderIndexResponse.class, omallHttpUtils.Obj2Map(orderIndexQueryBO));
                if (!CollectionUtil.isEmpty(orderIndexResponse.getOrderInfoList())) {
                    convert(mulPlatformUser, orderIndexResponse.getOrderInfoList());
                }
            }
            //一个用户订单同步完成更新Omall_sync_infot表
//            OmallSyncInfo omallSyncInfo = new OmallSyncInfo();
            Date date = DateUtil.parseDate(orderIndexQueryBO.getEndTime());
//            omallSyncInfo.setLastImportTradeTime(date);
            UpdateWrapper updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id", mulPlatformUser.getUserId());
            updateWrapper.eq("company_id", mulPlatformUser.getCompanyId());
            updateWrapper.set("last_import_trade_time", date);
            omallSyncInfoService.update(updateWrapper);
        }

    }

    /**
     * 转换成Trade
     *
     * @param user
     * @param orderList
     * @return
     */
    public void convert(MulPlatformUser user, List<OrderListInfo> orderList) {
        for (OrderListInfo orderListInfo : orderList) {
            List<RefundInfo> refundInfos = getRefundDetail(orderListInfo.getPlatformCode(), user);
            List<OrderDetail> orderDetails = getOrderDetail(orderListInfo.getPlatformCode(), user);
            TradeCopierVo tradeCopierVo = new TradeCopierVo();
            tradeCopierVo.setRefundInfos(refundInfos);
            BeanUtil.copyProperties(orderListInfo, tradeCopierVo);
            List<OrderCopierVo> orderCopierVoList = new ArrayList<>();
            for (OrderDetail orderDetail : orderDetails) {
                OrderCopierVo orderCopierVo = new OrderCopierVo();
                BeanUtil.copyProperties(orderDetail, orderCopierVo);
                orderCopierVoList.add(orderCopierVo);
            }
            //设置订单详细信息方便后续计算订单的实付金额
            tradeCopierVo.setOrderDetails(orderCopierVoList);
            TbTradeBO tbTradeBO = omallTradeCopier.copy(tradeCopierVo, TradeUtils.initTradeUserInfo(new Trade(), user));
            Trade trade = tbTradeBO.getTrade();
            if (tradeService.save(trade)) {
                orderService.saveBatch(tbTradeBO.getOrderList());
            }

        }
    }

    /***
     * @DESCRIPTION: 订单详细信息
     * @author 枫伦
     * @params: [platformCode, user]
     * @return: java.util.List<com.omall.open.sdk.domain.OrderDetail>
     * @Date: 2021/1/8 5:06 下午
     * @Modified By:  
     */
    @Override
    public List<OrderDetail> getOrderDetail(String platformCode, MulPlatformUser user) {
        Map headmap = omallHttpUtils.getHeadMap(user);
        OrderDetailBO orderDetailBO = new OrderDetailBO();
        orderDetailBO.setPlatformCode(platformCode);
        try {
            OrderDetailResponse orderDetailResponse = (OrderDetailResponse) omallHttpUtils.requestWithParams(Method.POST, Constants.RequestUrl.ORDER_DETAIL, headmap, OrderDetailResponse.class, omallHttpUtils.Obj2Map(orderDetailBO));
            if (orderDetailResponse.isSuccess()) {
                return orderDetailResponse.getOrderDetailList();
            }
        } catch (Exception e) {
            e.printStackTrace();
//            log.error(LogHelper.buildErrorLog(user, e, e.getMessage()));
            throw new RuntimeException("omall订单明细查询接口调用失败");
        }
        return new ArrayList<>();
    }

    /***
     * @DESCRIPTION: 售后单查询
     * @author 枫伦
     * @params: [platformCode, user]
     * @return: java.util.List<com.omall.open.sdk.domain.RefundInfo>
     * @Date: 2021/1/8 3:28 下午 
     * @Modified By:  
     */
    @Override
    public List<RefundInfo> getRefundDetail(String platformCode, MulPlatformUser user) {
        Map headmap = omallHttpUtils.getHeadMap(user);
        ReturnOrderIndexBO returnOrderIndexBO = new ReturnOrderIndexBO();
        returnOrderIndexBO.setPlatformOrderCode(platformCode);
        try {
            RefundResponse response = (RefundResponse) omallHttpUtils.requestWithParams(Method.POST, Constants.RequestUrl.RETURN_ORDER_INDEX, headmap, RefundResponse.class, omallHttpUtils.Obj2Map(returnOrderIndexBO));
            if (response.isSuccess()) {
                return response.getRefundInfoList();
            }
        } catch (Exception e) {
            e.printStackTrace();
//            Log.error(LogHelper.buildErrorLog(user, e, e.getMessage()));
            throw new RuntimeException("omall退款明细查询接口调用失败");
        }
        return new ArrayList<>();
    }
}
